package com.bw.lib_common.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bw.lib_common.base.state.RequestEvent
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * @author ytx
 * @date 2025-09-17 15:40
 * @description
 */
abstract class BaseFragment<VM:BaseViewModel,VDB: ViewDataBinding>:Fragment() {
    protected lateinit var mBinding:VDB //dataBinding
    protected abstract val mLayoutResId:Int //布局id
    protected lateinit var mParentView: View //view

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = DataBindingUtil.inflate(inflater,mLayoutResId,container,false)
        mBinding.lifecycleOwner = this
        mParentView = mBinding.root
        return mParentView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initListener()
        initData()
    }
    open fun initView(){}
    open fun initData(){}
    open fun initListener(){}

    /**
     * 隐藏键盘
     */
    fun hideSoftKeyBroad(view:View){
        if(requireActivity() is BaseActivity<*,*>){
            (requireActivity() as BaseActivity<*,*>).hideKeyboard(view)
        }
    }
    /**
     * 显示键盘
     */
    fun dismissKeyboard(){
        if(activity is BaseActivity<*,*>){
            (requireActivity() as BaseActivity<*,*>).dismissKeyboard()
        }
    }
    /**
     * 显示键盘
     */
    fun showSoftKeyBroad(view:View){
        if(activity is BaseActivity<*,*>){
            (requireActivity() as BaseActivity<*,*>).showSoftKeyBoard(view)
        }
    }
    fun setLoadingViewVisible(show:Boolean,msg:String = ""){
        if(activity is BaseActivity<*,*>){
            (requireActivity() as BaseActivity<*,*>).setLoadingViewVisible(show,msg)
        }
    }

    fun addCommonStateListener(flow: StateFlow<RequestEvent>){
        if(activity is BaseActivity<*,*>){
            (requireActivity() as BaseActivity<*,*>).addCommonStateListener(flow)
        }
    }



}